﻿package com.midia.playerVideo.controles {
	import flash.display.MovieClip;	
	import flash.display.MovieClip;
	
	import flash.geom.Rectangle;
	
	import flash.events.Event;
	import flash.events.MouseEvent;	
	import flash.events.EventDispatcher;
	
	import com.midia.playerVideo.events.BarraEvent;
		
	public class Barra extends MovieClip {
		
		public static var DRAG_MOVE:String = "dragMove";
		
		private var _perc:int;
		private var esquerda:Number;
		private var direita:Number;
		private var hMax:Number;
		
		public function Barra ():void {
			this.drag.addEventListener (MouseEvent.MOUSE_DOWN, this.onStartDrag);
			this.drag.addEventListener (MouseEvent.MOUSE_UP, this.onStopDrag);	
			
			this.areaSeek.addEventListener (MouseEvent.MOUSE_DOWN, this.onDownArea);	
			
			this.esquerda = 0;
			this.direita = 0;
			
			this.hMax = this.area.height - this.drag.height;
		}
		
		public function get perc ():int {
			return this._perc;
		}
		
		public function set perc (valor:int):void {
			this._perc = valor;
			this.drag.y = Math.ceil( (100 - this._perc) * this.hMax / 100);
		}
		
		private function onDownArea (evento:MouseEvent):void {
			var objeto:MovieClip = MovieClip (evento.target);
			var perc:Number = 100 - Math.ceil(objeto.mouseY / this.hMax * 100);
			this.drag.y = ((100 - perc) * this.hMax / 100);
			if (this.drag.y > this.hMax) {
				this.drag.y = this.hMax;
			}
			var evt:BarraEvent = new BarraEvent(DRAG_MOVE);
			evt.perc = perc;
			this.dispatchEvent(evt);
		}
		
		private function onStartDrag (evento:MouseEvent):void {
			var rect:Rectangle = new Rectangle (this.esquerda, this.area.y, this.direita, this.hMax);
			this.drag.startDrag (false, rect);
			this.drag.addEventListener (MouseEvent.MOUSE_MOVE, this.onMoveDrag);
			this.stage.addEventListener (MouseEvent.MOUSE_UP, this.onStopDrag);
			this.stage.addEventListener (MouseEvent.MOUSE_MOVE, this.onMoveDrag);
		}
		
		private function onStopDrag (evento:MouseEvent):void {
			this.drag.stopDrag ();
			this.stage.removeEventListener (MouseEvent.MOUSE_UP, this.onStopDrag);
			this.stage.removeEventListener (MouseEvent.MOUSE_MOVE, this.onMoveDrag);
			this.drag.removeEventListener (MouseEvent.MOUSE_MOVE, this.onMoveDrag);
		}
		
		private function onMoveDrag (evento:Event):void {
			this._perc = 100 - Math.ceil(this.drag.y / this.hMax * 100); 
			var evt:BarraEvent = new BarraEvent(DRAG_MOVE);
			evt.perc = this._perc;
			this.dispatchEvent(evt);
		}
	}	
}